package com.budwk.app.sqfwV2.controller;

import cn.dev33.satoken.annotation.SaCheckLogin;
import com.alibaba.excel.util.StringUtils;
import com.alibaba.fastjson.JSONObject;
import com.budwk.app.exception.ServiceException;
import com.budwk.app.sqfw.enums.SupportBusinessTypeEnum;
import com.budwk.app.sqfw.models.Sqfw_formSummary_new;
import com.budwk.app.sqfw.vo.GenerateExcelUrlVO;
import com.budwk.app.sqfwDoc.dto.CompleteFlowTemplateCodeUpdateDTO;
import com.budwk.app.sqfwV2.dto.PlaceParamDTO;
import com.budwk.app.sqfwV2.dto.dto.SqfwShopBaseInfoDTO;
import com.budwk.app.sqfwV2.dto.dto.dayingRoad.DownExcelLedgerReqVo;
import com.budwk.app.sqfwV2.dto.dto.dayingRoad.DownFileTypesResVo;
import com.budwk.app.sqfwV2.dto.entity.SqfwShopsBaseInfo;
import com.budwk.app.sqfwV2.dto.vo.SummaryQueryReqVo;
import com.budwk.app.sqfwV2.enums.publicSecurity.PublicSecurityFileEnum;
import com.budwk.app.sqfwV2.service.publicSecurity.PublicSecurityService;
import com.budwk.starter.common.openapi.annotation.ApiDefinition;
import com.budwk.starter.common.openapi.annotation.ApiFormParams;
import com.budwk.starter.common.openapi.annotation.ApiOperation;
import com.budwk.starter.common.openapi.annotation.ApiResponses;
import com.budwk.starter.common.result.Result;
import com.budwk.starter.log.annotation.SLog;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.compress.utils.Lists;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.mvc.annotation.*;
import org.springframework.util.ObjectUtils;

import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * @author zhangp
 * @description 社会治安
 * @className PublicSecurityController
 * @Date 14:49 2024/3/25
 */
@IocBean
@At("/platform/sqfwV2/publicSecurity")
@ApiDefinition(tag = "社会治安）")
@Slf4j
public class PublicSecurityController {

    @Inject
    private PublicSecurityService publicSecurityService;

    @At
    @Ok("json")
    @POST
    @ApiOperation(name = "保存数据并创建pdf")
    @SLog(tag = "保存数据并创建pdf", value = "${args[0]}")
    public Result<?> submitData(@Param("..") CompleteFlowTemplateCodeUpdateDTO dto) {
        log.info("PublicSecurityController submitData param: {}", JSONObject.toJSONString(dto));
        return Result.data(publicSecurityService.submitData(dto));
    }

    @At
    @Ok("json")
    @GET
    @ApiOperation(name = "重新生成PDF")
    @SaCheckLogin
    public Result<?> reGeneratePDF(@Param("sqfwFlowId") String sqfwFlowId) {
        log.info("PublicSecurityController reGeneratePDF sqfwFlowId: {}", sqfwFlowId);
        return publicSecurityService.reGeneratePDF(sqfwFlowId);
    }

    @At
    @Ok("json")
    @POST
    @ApiOperation(name = "下载Excle台账(按照编码下载)（支持批量下载）")
    @ApiResponses(implementation = GenerateExcelUrlVO.class)
    @SaCheckLogin
    public Result<?> downExcelLedger(@Param("..") DownExcelLedgerReqVo reqVo) {
        log.info("PublicSecurityController downExcelLedger reqVo: {}", JSONObject.toJSONString(reqVo));
        reqVo.setAgainGenerate(true);
        return publicSecurityService.downExcelLedger(reqVo);
    }

    @At
    @Ok("json")
    @POST
    @ApiOperation(name = "下载PDF")
    @ApiResponses(implementation = GenerateExcelUrlVO.class)
    @SaCheckLogin
    public Result<?> downPdfLedger(@Param("..") DownExcelLedgerReqVo reqVo) {
        log.info("PublicSecurityController downPdfLedger reqVo: {}", JSONObject.toJSONString(reqVo));
        reqVo.setAgainGenerate(true);
        return publicSecurityService.downPdfLedger(reqVo);
    }


    @At
    @Ok("json")
    @POST
    @ApiOperation(name = "批量数据检测")
    @ApiResponses(implementation = GenerateExcelUrlVO.class)
    @SaCheckLogin
    public Result<?> isCheckDataBatch(@Param("sqfwIdList") List<String> sqfwIdList) {
        log.info("PublicSecurityController isCheckDataBatch reqVo: {}", JSONObject.toJSONString(sqfwIdList));
        return Result.data(publicSecurityService.isCheckDataBatch(sqfwIdList));
    }

    @At
    @Ok("json")
    @GET
    @ApiOperation(name = "模板下载")
    @SaCheckLogin
    public Result<?> downloadTemplate(@Param("index") String index, HttpServletResponse response) {
        log.info("PublicSecurityController downloadTemplate reqVo: {}", index);
        return publicSecurityService.downloadTemplate(index, null);
    }

    @At
    @Ok("json")
    @GET
    @ApiOperation(name = "根据输入的查询条件和内容查询商铺名称信息")
    @ApiResponses(implementation = SqfwShopsBaseInfo.class)
    @SaCheckLogin
    public Result<?> getShopInfoListByContent(@Param("content") String content, @Param("pageSize") Integer pageSize, @Param("pageNo") Integer pageNo, @Param("types") List<String> types) {
        log.info("PublicSecurityController getShopInfoListByContent content: {},pageSize{},pageNo{},types{}", content, pageSize, pageNo, types);
        return publicSecurityService.getShopInfoListByContent(content, pageSize, pageNo, types);
    }


    @At
    @Ok("json")
    @GET
    @ApiOperation(name = "根据选择的商铺ID查询最新的记录")
    @ApiResponses(implementation = Sqfw_formSummary_new.class)
    @SaCheckLogin
    public Result<?> getFormSummaryInfoListByShopId(@Param("shopBaseInfoId") String shopBaseInfoId) {
        log.info("PublicSecurityController getFormSummaryInfoListByContent shopBaseInfoId: {}", shopBaseInfoId);
        return publicSecurityService.getFormSummaryInfoListByShopId(shopBaseInfoId);
    }

    /**
     * 根据当前登录人获取辖区商铺信息
     *
     * @return
     */
    @At("/getPlaceInfoList")
    @Ok("json")
    @POST
    @ApiOperation(name = "根据当前登录人获取社会治安场所")
    @ApiResponses
    @SLog(tag = "根据当前登录人获取社会治安场所", value = "")
    @SaCheckLogin
    public Result<?> getPlaceInfoList(@Param("status") String status, @Param("pageNo") Integer pageNo, @Param("pageSize") Integer pageSize, @Param("content") String content) {
        log.info("PublicSecurityController.getPlaceInfoList 请求参数：status：{},pageNo{},pageSize{}，content：{}", status, pageNo, pageSize, content);
        List<SqfwShopBaseInfoDTO> vo = publicSecurityService.getPlaceInfoList(status, pageNo, pageSize, content);
        return Result.data(vo);
    }

    @At
    @Ok("json")
    @POST
    @ApiOperation(name = "分页查询summary表数据")
    @ApiFormParams(implementation = SummaryQueryReqVo.class)
    @SaCheckLogin
    public Result<?> getFormSummaryPage(@Param("..") PlaceParamDTO dto) {
        log.info("PublicSecurityController getPublicSecurityFormSummaryPage param: {}", JSONObject.toJSONString(dto));
        return publicSecurityService.getPublicSecurityFormSummaryPage(dto);
    }

    @At
    @Ok("json")
    @GET
    @ApiOperation(name = "生成上报材料（检测数据）")
    @ApiResponses(implementation = DownFileTypesResVo.class)
    @SaCheckLogin
    public Result<?> getReportMaterials(@Param("fillStartDate") String fillStartDate, @Param("fillEndDate") String fillEndDate, @Param("serviceType") String serviceType, @Param("shopInfoId") String shopInfoId,@Param("fileMark") String fileMark,@Param("placeType") String placeType) {
        log.info("PublicSecurityController getReportMaterials fillStartDate: {},fillEndDate{},serviceType:{},shopInfoId:{},fileMark:{},placeType:{}", fillStartDate, fillEndDate, serviceType,shopInfoId,fileMark,placeType);
        if (StringUtils.isBlank(serviceType)) {
            serviceType = SupportBusinessTypeEnum.PUBLIC_SECURITY.getName();
        }
        return publicSecurityService.getReportMaterials(fillStartDate, fillEndDate, serviceType,shopInfoId,fileMark,placeType);
    }

    @At
    @Ok("json")
    @POST
    @ApiOperation(name = "下载文件")
    @ApiResponses(implementation = GenerateExcelUrlVO.class)
    @SaCheckLogin
    public Result<?> downloadFile(@Param("..") DownExcelLedgerReqVo reqVo) {
        log.info("PublicSecurityController downDataFile reqVo: {}", JSONObject.toJSONString(reqVo));

        if (StringUtils.isBlank(reqVo.getDownFileType())) {
            throw new ServiceException("下载文件类型不能为空！");
        }
        /*if (ObjectUtils.isEmpty(reqVo.getExcelCodes()) || reqVo.getExcelCodes().isEmpty()) {
            throw new ServiceException("下载文件索引不能为空不能为空！");
        }*/
        if (ObjectUtils.isEmpty(reqVo.getFileCode())) {
            throw new ServiceException("下载文件索引不能为空！");
        }
        PublicSecurityFileEnum publicSecurityFileEnum = PublicSecurityFileEnum.getPublicSecurityFileByCode(reqVo.getFileCode());
        if (ObjectUtils.isEmpty(publicSecurityFileEnum)) {
            throw new ServiceException("下载失败,下载文件不存在！");
        }
        String fileType = publicSecurityFileEnum.getSuffix().equalsIgnoreCase("docx") ? "pdf" : "excel";
        if (!fileType.equalsIgnoreCase(reqVo.getDownFileType())) {
            throw new ServiceException("下载文件类型与文件不匹配！");
        }
        List<String> fileCodes = Lists.newArrayList();
        fileCodes.add(reqVo.getFileCode());
        reqVo.setExcelCodes(fileCodes);
        //下载模板
        if (reqVo.isDownTemplate()) {
            List<GenerateExcelUrlVO> generateExcelUrlVOS = Lists.newArrayList();
            GenerateExcelUrlVO vo = publicSecurityService.downloadTemplateByIndex(reqVo.getExcelCodes().get(0));
            generateExcelUrlVOS.add(vo);
            return Result.data(generateExcelUrlVOS);
        } else {
            //下载数据
            if ("PDF".equalsIgnoreCase(reqVo.getDownFileType())) {
                return downPdfLedger(reqVo);
            } else if ("EXCEL".equalsIgnoreCase(reqVo.getDownFileType())) {
                //兼容老数据，默认传一个值
                reqVo.setSqfwIds(List.of("0"));
                return downExcelLedger(reqVo);
            } else {
                throw new ServiceException("下载的文件类型不存在！");
            }
        }
    }

}
